<template>
  <div class="app-container customer-div">
    <div  v-show="goodsClassList.length > 0">
      <div>
        <el-menu :default-active="params.tab" class="el-menu-demo" mode="horizontal" @select="changeTab">
          <el-menu-item :index="item" v-for="item in goodsClassList" :key="item">{{item}}</el-menu-item>
        </el-menu>
        <div id="chart-div">
          <div class="tiaojian-div" style="padding-top:20px">
            <el-form :inline="true" :model="params" size="mini" label-width="90px">
              <el-form-item label="选择商品：">
                <el-select v-model="params.goodsKingId" class="input-width" style="width:195px" placeholder="请选择" clearable @change="changeParams" filterable>
                  <el-option :value="item.kingId" :label="item.goodsSn" :key="item.kingId" v-for="item in options"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="下单时间：">
                <el-date-picker
                        :default-time="['00:00:00', '23:59:59']"
                        @change="changeParams"
                        v-model="params.createDate"
                        type="daterange"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          <div id="myChart" :style="{'height':'550px'}" v-loading="loadingChart"></div>
        </div>
      </div>
      <!--数据列表-->
      <el-card class="box-card" v-if="isShow">
        <div class="table-container" >
          <div slot="header">{{params.date}} {{params.tab}} {{curtGoodsSn}} {{params.name}} 明细</div>
          <el-table
                  v-if="params.name=='日销售总量' || params.name=='销售现金均价'"
                  v-loading="loading"
                  :data="list"
                  border
                  style="width: 100%; margin-top: 20px">
            <el-table-column
                    prop="createTime"
                    label="订单时间"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="orderSn"
                    label="订单号"
                    align="center">
              <template slot-scope="scope">
                <el-link @click="toOrderDetail(scope.row.orderId)" type="primary" style="font-size:12px">
                  {{scope.row.orderSn}}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column
                    label="客户编号">
              <template slot-scope="scope">
                <el-link @click="toCustomerDetail(scope.row)" type="primary"  style="font-size:12px">
                  {{scope.row.customerNumber }}
                </el-link>
                <!--是否有权限-->
                <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
              </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="userRealName"
                    label="业务员">
            </el-table-column>
            <el-table-column
                    prop="goodsName"
                    label="商品名称">
            </el-table-column>
            <el-table-column
                    prop="goodsPrice"
                    label="合同单价"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsCashPrice"
                    label="现金价"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsNum"
                    label="合同数量"
                    align="center">
            </el-table-column>
          </el-table>
          <el-table
                  v-if="params.name=='日采购总量' || params.name=='采购现金均价'"
                  v-loading="loading"
                  :data="list"
                  border
                  style="width: 100%; margin-top: 20px">
            <el-table-column
                    prop="createDate"
                    label="订单时间"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="orderSn"
                    label="订单号"
                    align="center">
              <template slot-scope="scope">
                {{scope.row.orderSn}}
              </template>
            </el-table-column>
            <el-table-column
                    prop="supplierName"
                    label="供应商名称">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="userRealName"
                    label="采购员">
            </el-table-column>
            <el-table-column
                    prop="goodsSn"
                    label="商品">
            </el-table-column>
            <el-table-column
                    prop="goodsPrice"
                    label="采购单价"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsCashPrice"
                    label="现金价"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsNum"
                    label="采购量"
                    align="center">
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  layout="total, sizes,prev, pager, next,jumper"
                  :current-page.sync="params.pageNum"
                  :page-size="params.pageSize"
                  :page-sizes="[10,15,20]"
                  :total="count">
          </el-pagination>
        </div>
      </el-card>


      <!--数据列表-->
      <div class="tiaojian-div" style="margin-top:50px;clear: both;border-top:1px solid #eee;padding-top:40px">
        <el-form :inline="true" :model="params2" size="mini" label-width="90px" :rules="rules">
          <el-form-item label="选择商品：">
            <el-select v-model="params2.goodsKingId" class="input-width" style="width:195px" placeholder="请选择" clearable  filterable>
              <el-option :value="item.kingId" :label="item.goodsSn" :key="item.kingId" v-for="item in options"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间：">
            <el-date-picker
                    :default-time="['00:00:00', '23:59:59']"
                    v-model="params2.createDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="客户编号：">
            <el-input v-model="params2.customerNumber"></el-input>
<!--            <el-autocomplete-->
<!--                    clearable-->
<!--                    class="inline-input"-->
<!--                    value-key="customerName"-->
<!--                    :fetch-suggestions="querySearch"-->
<!--                    v-model="params2.customerName"-->
<!--                    placeholder="请输入内容"-->
<!--                    @select="handleSelectCustomerName"-->
<!--                    :trigger-on-focus="false"-->
<!--            ></el-autocomplete>-->
          </el-form-item>
          <el-form-item label="销售单价：" >
            <el-form-item label="" label-width="0" prop="minPrice">
                <el-input v-model="params2.goodsMinPrice" placeholder="最低价" style="width:100px;"></el-input>
            </el-form-item>
            <span> - </span>
            <el-form-item label="" label-width="0" style="margin-left:10px" prop="maxPrice">
              <el-input v-model="params2.goodsMaxPrice" placeholder="最高价" style="width:100px;" ></el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-button
                    @click="handleSearchList2()"
                    type="primary">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-container" style="margin-top:0">
        <el-table
                v-loading="loading2"
                :data="list2"
                border
                style="width: 100%;margin-top:0">
          <el-table-column
                  prop="createTime"
                  label="订单时间"
                  align="center">
          </el-table-column>
          <el-table-column
                  prop="orderSn"
                  label="订单号"
                  align="center">
            <template slot-scope="scope">
              <el-link @click="toOrderDetail(scope.row.orderId)" type="primary" style="font-size:12px">
                {{scope.row.orderSn}}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
                  prop="customerName"
                  label="客户编号">
            <template slot-scope="scope">
              <el-link @click="toCustomerDetail(scope.row)" type="primary"  style="font-size:12px">
                {{scope.row.customerNumber }}
              </el-link>
              <!--是否有权限-->
              <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  prop="userRealName"
                  label="业务员">
          </el-table-column>
          <el-table-column
                  prop="goodsName"
                  label="商品名称">
          </el-table-column>
          <el-table-column
                  prop="goodsPrice"
                  label="合同单价"
                  align="center">
          </el-table-column>
          <el-table-column
                  prop="goodsNum"
                  label="合同数量"
                  align="center">
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
                background
                @size-change="handleSizeChange2"
                @current-change="handleCurrentChange2"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="params2.pageNum"
                :page-size="params2.pageSize"
                :page-sizes="[10,15,20]"
                :total="count2">
        </el-pagination>
      </div>
    </div>
    <div v-show="showDiv && goodsClassList.length == 0" style="text-align:center;padding:40px;color:#333;height:500px">
        <div style="padding-bottom:10px"><i class="el-icon-circle-close" style="font-size:48px;color:red"></i></div>抱歉，您无权限查看
    </div>


  </div>
</template>

<script>
    import { myGoodsClass,goodsReport,getSaleDetailList,purchaseOrderGoodsList,getCustomerOption} from '@/api/partner'
    import {goodsList} from '@/api/company'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import {validateCommission} from '@/utils/validate';

    export default {
        name: "goodsAnalysis",
        data(){
          const minPrice = (rule, value, callback) => {
            let MinPrice = this.params2.goodsMinPrice !='' ? parseFloat(this.params2.goodsMinPrice) : '';
            let MaxPrice = this.params2.goodsMaxPrice !='' ? parseFloat(this.params2.goodsMaxPrice) : '';
            if(MinPrice == ''){
              callback()
            }else if (!validateCommission(parseFloat(MinPrice))) {
              this.params2.goodsMinPrice = '';
              callback()
            } else if(MaxPrice != ''  && MinPrice > MaxPrice){
              this.params2.goodsMinPrice = MaxPrice;
              callback()
            }else {
              callback()
            }
          };
          const maxPrice = (rule, value, callback) => {
            let MinPrice = this.params2.goodsMinPrice !='' ? parseFloat(this.params2.goodsMinPrice) : '';
            let MaxPrice = this.params2.goodsMaxPrice !='' ? parseFloat(this.params2.goodsMaxPrice) : '';
            if(MaxPrice == ''){
              callback()
            }else if (!validateCommission(parseFloat(MaxPrice))) {
              this.params2.goodsMaxPrice = '';
              callback()
            } else if(MinPrice != ''  && MaxPrice < MinPrice){
              this.params2.goodsMaxPrice = MinPrice;
              callback()
            }else {
              callback()
            }
          };
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                params:{
                  pageNum:1,
                  pageSize:10,
                  createDate:[],
                  goodsKingId:'',
                  tab:'PA6',
                  name:'',
                  date:'',
                },
                list:[],
                count:0,
                loading:false,
                chartW:0,
                loadingChart:false,
                isShow:false,
                options:[],
                curtGoodsSn:'',
                goodsClassList:[],
                showDiv:false,
                tableTab:'',
                params2:{
                  pageNum:1,
                  pageSize:10,
                  createDate:[],
                  goodsKingId:'',
                  customerName:'',
                  goodsMinPrice:'',
                  goodsMaxPrice:'',
                  customerNumber:''
                },
                list2:[],
                count2:0,
                loading2:false,
                rules:{
                  minPrice :[{ trigger: 'blur' ,validator: minPrice}],
                  maxPrice :[{ trigger: 'blur' ,validator: maxPrice}],
                },
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),


        },
        created() {
          this.showDiv = false;
          this.getMyGoodsClass().then(()=>{
            this.showDiv = true;
            if(this.goodsClassList.length > 0){
              this.getGoodsReport();
            }
          })

          this.getGoodsList();
          setTimeout(()=>{
            this.chartW = $("#chart-div").width();
          },300);
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
          //去客户详情页
          toCustomerDetail(item){
            let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
            window.open(routeData.href);
          },
          //去订单详情页
          toOrderDetail(orderId){
            let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:orderId,type:'see',seeType:'caiWu'}});
            window.open(routeData.href);
          },

          //获取我的商品分类
          getMyGoodsClass(){
            return myGoodsClass(). then((res)=>{
                this.goodsClassList = res;
                this.params.tab=res[0] ? res[0] : ''
              })
          },
          //获取商品列表
            getGoodsList(){
                goodsList({goodsName:this.params.tab}).then((res)=>{
                    this.options = res.list;
                })
            },
            //切换分类
            changeTab(key){
                this.params.tab = key;
                this.params.goodsKingId = '';
                this.clearTable();
                this.getGoodsReport();
                this.getGoodsList();
                this.params2.goodsKingId = '';
                this.list2 = [];
                this.count2 = 0;

            },
            //切换图表参数
            changeParams(){
                this.clearTable();
                if(this.params.goodsKingId){
                    let goodsSn= this.options.find((el)=>{
                        return el.kingId == this.params.goodsKingId
                    });
                    this.curtGoodsSn = goodsSn.goodsSn;
                }else{
                    this.curtGoodsSn = '';
                }

                this.getGoodsReport();
            },
            //清空数据表
            clearTable(){
                this.list = [];
                this.count = 0;
                this.isShow = false;
            },
            //获取图表数据
            getGoodsReport(){
                this.loadingChart = true;
                goodsReport({goodsName:this.params.tab,createDate:this.params.createDate,goodsKingId:this.params.goodsKingId}).then((res)=>{
                        let createDay = [];let purchaseNum = []; let purchasePrice = [];let saleNum = []; let salePrice = [];let goodsSnPrice = [];
                        res.forEach((el)=>{
                            createDay.push(el.createDay);
                            purchaseNum.push(el.purchaseNum);
                            purchasePrice.push(el.purchasePrice);
                            saleNum.push(el.saleNum);
                            salePrice.push(el.salePrice);
                          goodsSnPrice.push(el.goodsSnPrice)
                        });
                        setTimeout(()=>{
                             document.getElementById('myChart').removeAttribute('_echarts_instance_');
                            this.drawCaiGouCount(createDay,purchaseNum,purchasePrice,saleNum,salePrice,goodsSnPrice)
                        },600)

                })
            },
          //画图表
          drawCaiGouCount(createDay,purchaseNum,purchasePrice,saleNum,salePrice,goodsSnPrice){
            let myChart = this.$echarts.init(document.getElementById('myChart'));
            let next = createDay.length - 1;
            let array = [];
            array = purchasePrice.concat(salePrice,goodsSnPrice);
            array = array.filter((el)=>{
              return el != null
            });
            array = array.sort((a, b) => a - b)
            let min = array[0] ? array[0] : 0;
            // 绘制图表
            myChart.setOption({
              dataZoom: [{
                show: true,
              }, {
                type: 'inside'
              }],
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  crossStyle: {
                    color: '#999'
                  }
                }
              },
              legend: {
                data: ['日采购总量', '日销售总量', '采购现金均价','销售现金均价','摩塑网价格']
              },
              xAxis: [
                {
                  type: 'category',
                  data: createDay,
                  axisPointer: {
                    type: 'shadow'
                  }
                }
              ],
              yAxis: [
                {
                  type: 'value',
                  name: '价格',
                  axisLabel: {
                    formatter: '￥{value}'
                  },
                  min:min - 500 > 0 ? min - 500 : 0,
                  scale:true
                },
                {
                  type: 'value',
                  name: '数量',
                  axisLabel: {
                    formatter: '{value} 吨'
                  }
                },
              ],
              series: [
                {
                  name: '销售现金均价',
                  type: 'line',
                  smooth: true,
                  data: salePrice,
                  symbolSize: 10,   //设定实心点的大小
                  itemStyle: {
                    normal: {
                      //定义一个list，通过list获取颜色，
                      color: '#c71010'
                    }
                  },
                },
                {
                  name: '日销售总量',
                  type: 'bar',
                  yAxisIndex: 1,
                  data: saleNum,
                  itemStyle: {
                    normal: {
                      //定义一个list，通过list获取颜色，
                      color: '#c71010'
                    }
                  },
                },
                {
                  name: '采购现金均价',
                  type: 'line',
                  smooth: true,
                  symbolSize: 10,   //设定实心点的大小
                  data: purchasePrice,
                  itemStyle: {
                    normal: {
                      //定义一个list，通过list获取颜色，
                      color: '#1d9b00'
                    }
                  },
                },
                {
                  name: '日采购总量',
                  type: 'bar',
                  yAxisIndex: 1,
                  data: purchaseNum,
                  itemStyle: {
                    normal: {
                      //定义一个list，通过list获取颜色，
                      color: '#1d9b00'
                    }
                  },
                  label:{
                    show:true,
                    position:'top'
                  },
                },
                {
                  name: '摩塑网价格',
                  type: 'line',
                  smooth: true,
                  symbolSize: 10,   //设定实心点的大小
                  data: goodsSnPrice,
                  itemStyle: {
                    normal: {
                      //定义一个list，通过list获取颜色，
                      color: '#7200ff'
                    }
                  },
                },
              ]
            });
            this.loadingChart = false;
            myChart.on('click',(params)=>{
                this.isShow = true;
                this.list = [];
                this.count = 0;
                this.tableTab = 'date';
                this.params.name = params.seriesName;
                this.params.date = params.name;
                this.handleSearchList();
            });
            myChart.on('legendselectchanged', (obj)=> {
              console.log("123141234",obj);
              // if(obj.selected[obj.name]){
                this.isShow = true;
                this.list = [];
                this.count = 0;
                this.params.name = obj.name;
                this.tableTab = 'all';
                this.handleSearchList();
              // }

            })
          },
            handleSearchList(){
                this.params.pageNum = 1;
                this.getListData();
            },

            handleSizeChange(val){
                this.params.pageNum = 1;
                this.params.pageSize = val;
                this.getListData();
            },
            handleCurrentChange(val){
                this.params.pageNum = val;
                this.getListData();
            },

            getListData(){
              this.loading = true;
              let fn = null;
              let params = {};
              params.pageNum = this.params.pageNum;
              params.pageSize = this.params.pageSize;
              if(this.tableTab == 'date'){
                params.createDate=[this.params.date+' 00:00:00' ,this.params.date+' 23:59:59'];
              }else if(this.tableTab == 'all'){
                if(this.params.createDate[0]){
                  params.createDate=[this.params.createDate[0] ,this.params.createDate[1]];
                }else{
                  let start = new Date(new Date(new Date(new Date().getTime()).setHours(0,0,0,0)).getTime()-24 * 60 * 60 * 1000*30);
                  let end = new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 -1);
                  params.createDate = [formatDate(start, 'yyyy-MM-dd hh:mm:ss'),formatDate(end, 'yyyy-MM-dd hh:mm:ss')];
                }
              }
              if( this.params.name=='日销售总量' || this.params.name=='销售现金均价'){
                  fn = getSaleDetailList;
                  params.goodsName = this.params.tab;
                  params.goodsKingId = this.params.goodsKingId;
              }else{
                  fn = purchaseOrderGoodsList;
                  params.goodsName = this.params.tab;
                  params.goodsKingId = this.params.goodsKingId;
              }
              fn(params).then(response => {
                this.list = response.list;
                this.count = response.count;
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              });

            },

          //客户名称输入匹配
          querySearch(queryString, cb){
            getCustomerOption({keywords:queryString}).then((res)=>{
              cb(res);
            })
          },


          //选择客户名称
          handleSelectCustomerName(item){
            this.params2.customerName = item.customerName
          },

          handleSearchList2(){
            this.params2.pageNum = 1;
            this.getListData2();
          },

          handleSizeChange2(val){
            this.params2.pageNum = 1;
            this.params2.pageSize = val;
            this.getListData2();
          },
          handleCurrentChange2(val){
            this.params2.pageNum = val;
            this.getListData2();
          },

          getListData2(){
            this.loading2 = true;
            getSaleDetailList(this.params2).then(response => {
              this.list2 = response.list;
              this.count2 = response.count;
              this.loading2 = false;
            }).catch(()=>{
              this.loading2 = false;
            });

          },

        },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
